import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { cartService } from "@/services/cart";

export const useCartStore = defineStore("cartStore", () => {
  // 状态
  const cartList = ref([]);
  const isEdit = ref(false);
  const useLocalStorage = ref(false);

  // getters
  const cartCount = computed(() =>
    cartList.value.reduce((total, item) => total + item.quantity, 0)
  );

  const totalPrice = computed(() =>
    cartList.value
      .filter((item) => item.selected)
      .reduce((total, item) => total + item.salePrice * item.quantity, 0)
      .toFixed(2)
  );

  const selectedCount = computed(
    () => cartList.value.filter((item) => item.selected).length
  );

  const isAllSelected = computed(
    () =>
      cartList.value.length > 0 && cartList.value.every((item) => item.selected)
  );

  // 加载购物车数据
  async function loadCartData() {
    try {
      console.log('开始加载购物车数据');
      const res = await cartService.getCartList();
      console.log('购物车API返回数据:', res);
      
      if (res.success) {
        // 统一数据结构
        cartList.value = res.data.map(normalizeCartItem);
        console.log('处理后的购物车数据:', cartList.value);
        updateTabBarBadge();
      } else {
        console.log('加载购物车失败:', res);
      }
    } catch (error) {
      console.error("加载购物车数据失败:", error);
      throw error;
    }
  }

  // 更新商品数量
  async function updateQuantity(index, delta) {
    try {
      const item = cartList.value[index];
      console.log('要更新的商品:', item);
      
      const newQuantity = parseInt(item.quantity || 0) + delta;
      
      if (newQuantity < 1 || newQuantity > 99) {
        uni.showToast({
          title: newQuantity < 1 ? "数量不能小于1" : "数量不能超过99",
          icon: "none",
        });
        return;
      }

      // 乐观更新UI
      const originalQuantity = item.quantity;
      item.quantity = newQuantity;
      updateTabBarBadge();

      try {
        const cartId = parseInt(item.id);
        if (isNaN(cartId)) {
          throw new Error('无效的购物车ID');
        }
        
        const res = await cartService.updateCartQuantity(cartId, newQuantity);
        console.log('更新购物车响应:', res);
        
        if (!res.success) {
          // 如果更新失败，回滚UI
          item.quantity = originalQuantity;
          updateTabBarBadge();
          uni.showToast({
            title: res.message || "更新失败",
            icon: "none"
          });
        }
      } catch (error) {
        // 发生错误时回滚UI
        item.quantity = originalQuantity;
        updateTabBarBadge();
        console.error("更新购物车数量失败:", error);
        uni.showToast({
          title: "更新失败",
          icon: "none"
        });
      }
    } catch (error) {
      console.error("更新数量失败:", error);
      uni.showToast({
        title: "操作失败",
        icon: "none"
      });
    }
  }

  // 处理数量输入
  async function handleQuantityInput(index, value) {
    const quantity = parseInt(value);
    if (isNaN(quantity) || quantity < 1) {
      await updateCartItem(index, 1);
    } else if (quantity > 99) {
      await updateCartItem(index, 99);
      uni.showToast({
        title: "数量不能超过99",
        icon: "none",
      });
    } else {
      await updateCartItem(index, quantity);
    }
  }

  // 删除商品确认
  function confirmDelete(index) {
    uni.showModal({
      title: "提示",
      content: "确定要删除这个商品吗？",
      success: async (res) => {
        if (res.confirm) {
          await removeFromCart(index);
        }
      },
    });
  }

  // 删除选中商品确认
  function confirmDeleteSelected() {
    if (selectedCount.value === 0) {
      uni.showToast({
        title: '请选择要删除的商品',
        icon: 'none'
      });
      return;
    }
    
    uni.showModal({
      title: "提示",
      content: "确定要删除选中的商品吗？",
      success: async (res) => {
        if (res.confirm) {
          await deleteSelected();
        }
      },
    });
  }

  // 结算
  function settlement() {
    if (selectedCount.value === 0) return;
    uni.navigateTo({
      url: "/pages/order/create",
    });
  }

  // 切换编辑模式
  function toggleEdit() {
    isEdit.value = !isEdit.value;
  }

  // 从服务器加载购物车数据
  async function loadCartData() {
    try {
      if (useLocalStorage.value) {
        // 如果启用本地存储，先尝试从本地获取
        const localData = uni.getStorageSync("cartList");
        if (localData) {
          cartList.value = localData;
          updateTabBarBadge();
          return;
        }
      }

      // 从服务器获取数据
      const res = await cartService.getCartList();
      if (res.success) {
        cartList.value = res.data;
        if (useLocalStorage.value) {
          saveToStorage();
        } else {
          updateTabBarBadge();
        }
      }
    } catch (error) {
      console.error("加载购物车数据失败:", error);
    }
  }

  // 添加到购物车
  async function addToCart(goods) {
    if (useLocalStorage.value) {
      const existItem = cartList.value.find((item) => item.spuId === goods.spuId);
      if (existItem) {
        existItem.quantity += goods.quantity;
      } else {
        cartList.value.push({
          ...goods,
          selected: true,
        });
      }
      saveToStorage();
      return;
    }

    try {
      const res = await cartService.addToCart(goods);
      if (res.success) {
        await loadCartData();
      }
    } catch (error) {
      console.error("添加到购物车失败:", error);
      throw error;
    }
  }

  // 更新购物车商品数量
  async function updateCartItem(index, quantity) {
    if (useLocalStorage.value) {
      cartList.value[index].quantity = quantity;
      saveToStorage();
      return;
    }

    try {
      const item = cartList.value[index];
      const res = await cartService.updateCartQuantity(item.id, quantity);
      if (res.success) {
        await loadCartData();
      }
    } catch (error) {
      console.error("更新购物车数量失败:", error);
      throw error;
    }
  }

  // 从购物车移除
  async function removeFromCart(index) {
    try {
      const item = cartList.value[index];
      console.log('准备删除商品:', item);

      const cartId = parseInt(item.id);
      if (isNaN(cartId)) {
        throw new Error('无效的购物车ID');
      }

      // 乐观更新UI
      const removedItem = cartList.value.splice(index, 1)[0];
      updateTabBarBadge();

      // 调用API删除商品
      const res = await cartService.removeFromCart(cartId);
      console.log('删除商品响应:', res);

      if (res.success) {
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        // 删除失败，恢复商品
        cartList.value.splice(index, 0, removedItem);
        updateTabBarBadge();
        uni.showToast({
          title: res.message || '删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error("删除商品失败:", error);
      uni.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  }

  // 删除选中的商品
  async function deleteSelected() {
    try {
      const selectedItems = cartList.value.filter(item => item.selected);
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要删除���商品',
          icon: 'none'
        });
        return;
      }

      console.log('准备删除选中商品:', selectedItems);

      // 保存原始购物车列表，以便失败时恢复
      const originalList = [...cartList.value];
      
      // 乐观更新UI - 移除选中商品
      cartList.value = cartList.value.filter(item => !item.selected);
      updateTabBarBadge();

      // 批量删除选中商品
      try {
        for (const item of selectedItems) {
          const cartId = parseInt(item.id);
          if (!isNaN(cartId)) {
            await cartService.removeFromCart(cartId);
          }
        }

        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } catch (error) {
        // 删除失败，恢复原始列表
        cartList.value = originalList;
        updateTabBarBadge();
        throw error;
      }
    } catch (error) {
      console.error("删除选中商品失败:", error);
      uni.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  }

  function setItemSelected(index, selected) {
    cartList.value[index].selected = selected;
    if (useLocalStorage.value) {
      saveToStorage();
    }
  }

  function setAllSelected(selected) {
    cartList.value.forEach((item) => (item.selected = selected));
    if (useLocalStorage.value) {
      saveToStorage();
    }
  }

  // 保存到本地存储
  function saveToStorage() {
    if (useLocalStorage.value) {
      uni.setStorageSync("cartList", cartList.value);
    }
    updateTabBarBadge();
  }

  // 更新购物车角标
  function updateTabBarBadge() {
    try {
      const count = cartCount.value;
      // 获取当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const isTabBarPage = ['pages/index/index', 'pages/category/category', 'pages/cart/cart', 'pages/user/user'].includes(currentPage?.route);

      if (!isTabBarPage) {
        console.log('当前不是TabBar页面，跳过设置badge');
        return;
      }

      if (count > 0) {
        uni.setTabBarBadge({
          index: 2,
          text: count.toString(),
        }).catch(err => {
          console.log('设置TabBarBadge失败:', err);
        });
      } else {
        uni.removeTabBarBadge({
          index: 2,
        }).catch(err => {
          console.log('移除TabBarBadge失败:', err);
        });
      }
    } catch (error) {
      console.error('更新购物车角标失败:', error);
    }
  }

  // 切换存储模式
  function toggleStorageMode(useLocal) {
    useLocalStorage.value = useLocal;
    if (useLocal) {
      saveToStorage();
    }
  }

  // 添加数据转换函数
  function normalizeCartItem(item) {
    console.log('原始商品数据:', item);
    
    const normalized = {
      ...item,
      skuId: parseInt(item.skuId),  // 确保有正确的 skuId
      title: item.spuName || item.title,
      primaryImage: item.mainPic || item.primaryImage,
      salePrice: item.minPrice || item.salePrice,
    };
    
    console.log('标准化后的商品数据:', normalized);
    return normalized;
  }

  // 获取已选择的商品
  function getSelectedGoods() {
    return cartList.value.filter(item => item.selected).map(item => ({
      id: item.id,
      spuId: item.spuId,
      skuId: item.skuId,
      quantity: item.quantity,
      title: item.title,
      primaryImage: item.primaryImage,
      salePrice: item.salePrice,
      specs: item.specs || '',
      selected: item.selected
    }));
  }

  return {
    cartList,
    isEdit,
    useLocalStorage,
    cartCount,
    totalPrice,
    selectedCount,
    isAllSelected,
    loadCartData,
    updateQuantity,
    handleQuantityInput,
    confirmDelete,
    confirmDeleteSelected,
    deleteSelected,
    settlement,
    toggleEdit,
    setItemSelected,
    setAllSelected,
    toggleStorageMode,
    updateTabBarBadge,
    addToCart,
    saveToStorage,
    removeFromCart,
    getSelectedGoods,
  };
});
